#ifndef __MY_CLIENT__
#define __MY_CLIENT__

#include "Data_Man.hpp"
#include "httplib.h"
#include <windows.h>
namespace RBC
{
#define SERVER_IP "120.26.57.122"
#define SERVER_PORT 9090
	class Client
	{
	public:
		Client(const std::string& back_dir, const std::string& backup_file)
			:_back_dir(back_dir)
		{
			_data = new RBC::DataManager(backup_file);
		}
		~Client()
		{
			if(_data)
				delete _data;
		}
		bool IsNeedUpload(const std::string& filename)
		{
			std::string old_id;
			if (_data->GetOneByFilename(filename, &old_id) != false)
			{
				if (old_id == GetFileUniqueID(filename))//˵������ļ�û�б��޸Ĺ�
				{
					return false;
				}
			}
			RBC::FileUtil fu(filename);
			if (time(nullptr) - fu.LastMTime() <= 3)//�������ļ������ڱ��޸Ĺ�����Ҳ���ϴ�
			{
				return false;
			}
			return true;
		}
		bool run()
		{
			
			while (1)
			{
				RBC::FileUtil fu(_back_dir);
				std::vector<std::string> arr;
				fu.ScanDirectory(&arr);
				for (auto a : arr)
				{
					if (IsNeedUpload(a) == true)
					{
						RBC::FileUtil fu(a);
						if (Upload(a) == true)
						{
							std::string id = GetFileUniqueID(a);
							std::string filename = fu.FileName();
							_data->Update(filename, id);
						}
					}
				}
			}
			Sleep(1);
		}
	private:
		
		std::string GetFileUniqueID(const std::string& filename)//��ȡ�ļ�Ψһ��ʶ
		{
			std::string ret;
			RBC::FileUtil fu(filename);
			ret += fu.FileName();
			ret += "-";
			ret += std::to_string(fu.FileSize());
			ret += "-";
			ret += std::to_string(fu.LastMTime());
			return ret;
		}
		bool Upload(const std::string& filename)
		{
			//�ļ�����������
			RBC::FileUtil fu(filename);
			std::string body;
			fu.GetContent(&body);//�õ�����Ҫ�ϴ����ļ�����������

			httplib::Client client(SERVER_IP, SERVER_PORT);
			httplib::MultipartFormData item;
			item.content = body;
			item.content_type = "application/octet-stream";
			item.filename = fu.FileName();
			item.name = "file";
			httplib::MultipartFormDataItems items;
			items.push_back(item);
			auto res = client.Post("/upload", items);
			if (!res || res->status != 200)
			{
				return false;
			}
			return true;
		}
		std::string _back_dir;//Ҫ��ص��ļ���
		RBC::DataManager* _data;
	};
}

#endif // __MY_CLIENT__

